package br.ufc.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import net.sf.jsqlparser.JSQLParserException;
import br.ufc.parser.CustomStatement;
import br.ufc.parser.Predicate;
import br.ufc.parser.Query;
import br.ufc.parser.Value;

public class CsvLoader {

	private String path;

	public CsvLoader(String path) {
		this.path = path;
	}

	public QueriesLoad load(){
		return load(Integer.MAX_VALUE);
	}

	public QueriesLoad load(int limit){

		Collection<CustomStatement> statements = new ArrayList<CustomStatement>();
		List<String> dimensions = new ArrayList<String>();
		Map<String, Value> mins = new HashMap<String, Value>();
		Map<String, Value> maxs = new HashMap<String, Value>();

		BufferedReader in = null;
		try {
			in = new BufferedReader (
					new InputStreamReader (
							new ReverseLineInputStream(
									new File(path))));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		String cvsSplitBy = ";;";
		Set<Predicate> predicates;

		int i = 0;
		while(i++ < limit) {
			String line = null;
			try {
				line = in.readLine();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (line == null) {
				break;
			}
//			System.out.println(line);

			String[] lineCSV = line.split(cvsSplitBy);
			System.out.println(line);
/*			for(int k = 0; k < lineCSV.length; k++){
				System.out.println("token: " +lineCSV[k]);
			}*/
			String query = lineCSV[4];
//			for(int j = 0; j < lineCSV.length; j++){
//				System.out.println(j + " " + lineCSV[j]);
//			}

			CustomStatement q = new CustomStatement(query);
			statements.add(q);
			if(q.isSelect()){				
				predicates = q.getSelect().getPredicates();

				for(Predicate predicate: predicates){
					String key = predicate.getAttribute();
					Value value = predicate.getValue(); 
					if(!dimensions.contains(key)){
						dimensions.add(key);
						mins.put(key, value);
						maxs.put(key, value);
					}else{
						if(mins.get(key).compareTo(value) < 0){
							mins.remove(key);
							mins.put(key, value);
						}
						if(maxs.get(key).compareTo(value) > 0){
							maxs.remove(key);
							maxs.put(key, value);
						}
					}
				}
			}
		}    

		try {
			in.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return new QueriesLoad(statements, dimensions, maxs, mins);
	}
}
